package com.example.java.io;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

public class IOTester {

    private static final String READ_FILE_PATH
            = "C:\\Users\\mengtain\\IdeaProjects\\study-spring\\java\\src\\main\\resources\\MyFileToRead.txt";

    private static final String WRITE_FILE_PATH
            = "C:\\Users\\mengtain\\IdeaProjects\\study-spring\\java\\src\\main\\resources\\MyFileToWrite.txt";

    static {
        Path w = Path.of(WRITE_FILE_PATH);
        if (Files.exists(w)) {
            try {
                Files.delete(w);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            Files.createFile(w);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void readWriteFile() {
        try(InputStream in = Files.newInputStream(Path.of(READ_FILE_PATH), StandardOpenOption.READ);
            OutputStream os =  Files.newOutputStream(Path.of(WRITE_FILE_PATH), StandardOpenOption.WRITE);) {
            os.write(in.readAllBytes());
            os.flush();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void fileToBytes(){
        try(InputStream is = Files.newInputStream(Path.of(READ_FILE_PATH))) {
            byte[] bytes = is.readAllBytes();
            System.out.println(Arrays.toString(bytes));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void bytesToFile(){
        byte[] bytes = new byte[1024];
        bytes[0] = 0;
        try(OutputStream os = Files.newOutputStream(Path.of(WRITE_FILE_PATH))) {
            os.write(bytes);
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void bytesToObject(){
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos)){
            oos.writeObject("Hello World"); //写进oos中，也就是baos中
            oos.flush();//这句对oos没用
            try(InputStream bais = new ByteArrayInputStream(baos.toByteArray());
                ObjectInputStream ois =  new ObjectInputStream(bais)) {
                System.out.println(ois.readObject());
            }
        }catch (Exception ignored){
        }
    }

    public static void reader(){
    }

}
